package io.renren.modules.jxgk.controller;

import io.renren.common.annotation.SysLog;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.modules.jxgk.entity.ClassCourse2Entity;
import io.renren.modules.jxgk.service.ClassCourse2Service;
import io.renren.modules.jxgk.service.WebSocket;
import io.renren.modules.jxgkphone.entity.DateInfo;
import io.renren.modules.jxgkphone.service.ClassCourseService;
import io.renren.modules.pullin.DataConversion.TeachControlView;
import io.renren.modules.pullin.entity.BinzhiClassCourse;
import io.renren.modules.pullin.entity.ClassCourse;
import io.renren.modules.pullin.service.PullOutService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("ClassCourse2/")
public class ClassCourse2Controller {

    @Autowired
    ClassCourse2Service classCourse2Service;
    @Autowired
    WebSocket webSocket;
    @Autowired
    ClassCourseService classCourseService;

    @RequestMapping("Select")
    public R list(@RequestParam Map<String, Object> params){
        //查询列表数据
        Query query = new Query(params);
        List<ClassCourse2Entity> cse = classCourse2Service.queryList(query);
        int total = classCourse2Service.queryTotal(query);

        PageUtils pageUtil = new PageUtils(cse, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    @RequestMapping("SelectForEcharts")
    public R SelectForEcharts(@RequestParam Map<String, Object> params){
        //查询列表数据
        Query query = new Query(params);
        List<ClassCourse2Entity> cse = classCourse2Service.SelectForEchartsList(query);
        int total = classCourse2Service.SelectForEchartsTotal(query);

        PageUtils pageUtil = new PageUtils(cse, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    @RequestMapping("/Delete")
    public R delete(@RequestBody String[] indexs){
        classCourse2Service.deleteBatch(indexs);
        return R.ok();
    }
    @RequestMapping("/Insert")
    public R save(@RequestBody ClassCourse2Entity ste){
        classCourse2Service.save(ste);
        return R.ok();
    }
    @RequestMapping("/Info/{index}")
    public R info(@PathVariable("index") String index){
        ClassCourse2Entity cse = classCourse2Service.queryObject(index);
        return R.ok().put("ClassCourse2", cse);
    }
    @SysLog("修改用户")
    @RequestMapping("/Update")
    public R update(@RequestBody ClassCourse2Entity cse){
        classCourse2Service.update(cse);
        return R.ok();
    }
    @Autowired
    PullOutService pullOutService;



    /**
     * 上传文件
     */
    @RequestMapping("/upload")

    //事务如何实现？
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        //这里只写了elx一种，就是excel2003-2007这个版本的， 别用错了
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        //从文件中获取数据
        List<BinzhiClassCourse> binzhiClassCourses=excelToEntity(file.getInputStream());
        //插入数据库
       insertToDataBase(binzhiClassCourses);
        return R.ok().put("msg", "数据导入成功");
    }

    private void insertToDataBase(List<BinzhiClassCourse> binzhiClassCourses){
        int i=1;
        int j=1;
        double k=0;
        String errReason;
        String errId;
        String errPos;
        String erresult;
        TeachControlView tcv=new TeachControlView();
        for(BinzhiClassCourse t:binzhiClassCourses){
            List<ClassCourse> exist=pullOutService.findClassCourseByClassNameAndCourseId(t.getBJMC(),t.getXKKH());
            if(!exist.isEmpty()){//如果存在，删除
                pullOutService.DeleteClassCourseByClassNameAndCourseId(t.getBJMC(),t.getXKKH());
                System.out.println("log:数据重复,删除，本条第"+j+"条");
                j++;
            }
            if(t.getSKSJ()!=null){//上课时间为空，数据有误
                try {
                    //数据格式转换
                    List<ClassCourse> l=tcv.InformationSet(t.getXKKH(),t.getKCMC(),t.getBJMC(),t.getJSXM(),
                            t.getJSZGH(),"2","2017-2018",t.getSKDD(),t.getSKSJ(),t.getXSXY());
                    for(ClassCourse c:l){
                        String courseTime=SetCourseTime(c);
                        c.setCourse_time(courseTime);
                        pullOutService.insertClassCourse(c);
                        System.out.println("log:插入数据成功，本条第"+i+"条");
                        i++;
                    }
                }catch (Exception e){
                    errReason="班级课程信息错误原因:"+e+"\n";
                    errId="错误位置:"+i+"\n";
                    errPos="错误信息:"+t.getXKKH()+"\n";
                    erresult=errReason+errId+errPos;
                    tcv.appendMethodB("errInfo.txt",erresult);
                }
            }
            //发送websocket消息
            k++;
            webSocket.sendMessage(""+k/binzhiClassCourses.size()*100);
        }
    }
    private List<BinzhiClassCourse> excelToEntity(InputStream inputStream) {
        List<BinzhiClassCourse> classCourses=new ArrayList<>();
        HSSFWorkbook wb = null;
        //保存文件信息
        try {
            wb = new HSSFWorkbook(inputStream);
            // logger.debug(wb.getNumberOfSheets());
            HSSFSheet sheet = wb.getSheetAt(0);
            //直接把表头直接加上了，如果数据没错乱的话，可以直接导入。
            int firstRound=1;
            int position[]=new int[8];
            for(int i = sheet.getFirstRowNum();i<=sheet.getLastRowNum();i++){
                HSSFRow row = sheet.getRow(i);
                Iterator cells = row.cellIterator();
                //大脑有点当机，想不出更好点的办法了，先这样吧，用循环赋值
                BinzhiClassCourse temp=new BinzhiClassCourse();

                int j=1;


                //初始化数据在Excel中的位置
                while (cells.hasNext()&&firstRound==1){
                    HSSFCell cell = (HSSFCell) cells.next();
                    String s=cell.toString();
                    if(s.equals("班级名称"))
                        position[0]=j;
                    if(s.equals("教师姓名"))
                        position[1]=j;
                    if(s.equals("课程名称"))
                        position[2]=j;
                    if(s.equals("教师职工号"))
                        position[3]=j;
                    if(s.equals("上课地点"))
                        position[4]=j;
                    if(s.equals("上课时间"))
                        position[5]=j;
                    if(s.equals("选课课号"))
                        position[6]=j;
                    if(s.equals("学生学院"))
                        position[7]=j;
                    j++;
                }
                firstRound=2;
                while(cells.hasNext()&&firstRound!=1){
                    HSSFCell cell = (HSSFCell) cells.next();
                    String s=cell.toString();
                    if(j==position[0])
                        temp.setBJMC(s);
                    if(j==position[1])
                        temp.setJSXM(s);
                    if(j==position[2])
                        temp.setKCMC(s);
                    if(j==position[3])
                        temp.setJSZGH(s);
                    if(j==position[4])
                        temp.setSKDD(s);
                    if(j==position[5])
                        temp.setSKSJ(s);
                    if(j==position[6])
                        temp.setXKKH(s);
                    if(j==position[7])
                        temp.setXSXY(s);
                    j++;
                }
                classCourses.add(temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return classCourses;
    }
    @RequestMapping("/AddTimeLabel")
    public void AddTimeLabel(){
        String date;
        String time="";
        String courseTime;
        int i=1;
        List<ClassCourse2Entity> classCourse2EntityList=classCourse2Service.selectAll();
        for(ClassCourse2Entity temp:classCourse2EntityList){
            if(temp.getCourseWhichIndex().equals("1"))
                time="08:00:00";
            if(temp.getCourseWhichIndex().equals("3"))
                time="10:00:00";
            if(temp.getCourseWhichIndex().equals("5"))
                time="13:30:00";
            if(temp.getCourseWhichIndex().equals("7"))
                time="15:30:00";
            if(temp.getCourseWhichIndex().equals("9"))
                time="18:30:00";
            DateInfo dateInfo=new DateInfo();
            dateInfo.setCourseAcademicYear(temp.getCourseAcademicYear());
            dateInfo.setCourseAcademicTerm(temp.getCourseAcademicTerm());
            dateInfo.setCourseWhichWeek(temp.getCourseWhichWeek());
            dateInfo.setCourseWhichDay(temp.getCourseWhichDay());
            date=classCourseService.findDateByDateInfo(dateInfo);
            courseTime=date+" "+time;
            //填写到数据库
            classCourse2Service.updateCourseTime(courseTime,temp.getClassCourseId());
            System.out.println("更新数据完成，第"+i+"条");
            i++;
        }

    }
    public String SetCourseTime(ClassCourse classCourse){
        String date;
        String time="";
        String courseTime;
        if(classCourse.getCourse_which_index().equals("1"))
            time="08:00:00";
        if(classCourse.getCourse_which_index().equals("3"))
            time="10:00:00";
        if(classCourse.getCourse_which_index().equals("5"))
            time="13:30:00";
        if(classCourse.getCourse_which_index().equals("7"))
            time="15:30:00";
        if(classCourse.getCourse_which_index().equals("9"))
            time="18:30:00";
        DateInfo dateInfo=new DateInfo();
        dateInfo.setCourseAcademicYear(classCourse.getCourse_academic_year());
        dateInfo.setCourseAcademicTerm(classCourse.getCourse_academic_term());
        dateInfo.setCourseWhichWeek(classCourse.getCourse_which_week());
        dateInfo.setCourseWhichDay(classCourse.getCourse_which_day());
        date=classCourseService.findDateByDateInfo(dateInfo);
        courseTime=date+" "+time;
        return  courseTime;
    }
}